<template>
    <Dialog :app-dialog="appDialog">
        <div class="label_con">
            <el-radio-group v-if="batchTag" v-model="RadioTags.defaultVal" class="radio_list">
                <el-radio
                    v-for="item in RadioTags.seleTagOp"
                    :key="item.value"
                    :label="item.value"
                    class="radio_list_item">
                    <span class="radio_list_item_text">{{ item.name }}</span>
                    <el-tooltip :content="item.text" placement="bottom">
                        <div class="radio_list_item_icon radio_img">
                            <img src="@/assets/image/material/question.png" alt="" />
                        </div>
                    </el-tooltip>
                </el-radio>
            </el-radio-group>
            <template v-if="labelList.length > 0">
                <el-scrollbar max-height="400px">
                    <div v-for="item in labelList" :key="item.id" class="label_list">
                        <div class="label_title">{{ item.name }}：</div>
                        <el-scrollbar class="label_box" max-height="80px">
                            <div
                                v-for="k in item.tags"
                                :key="k.id"
                                :class="{ tag_item: true, pad_4_10: true, tag_item_active: k.selted }"
                                type="info"
                                effect="plain"
                                @click="k.selted = !k.selted">
                                {{ k.name }}
                            </div>
                        </el-scrollbar>
                    </div>
                </el-scrollbar>
            </template>
            <template v-else>
                <div class="no_data">
                    <img class="no_img" src="@/assets/noData.png" alt="" />
                    <div class="no_title">暂无数据</div>
                </div>
            </template>
            <div v-if="showCreatTag" class="new_group">
                <div class="label_title">
                    新建分组：
                    <el-switch v-model="isGroup" />
                </div>
                <el-form v-if="isGroup" ref="formRef" :model="groupData" label-width="100px" class="demo_dynamic">
                    <el-form-item
                        prop="name"
                        label="分组名称："
                        :rules="{ required: true, message: '分组名称不能为空', trigger: 'blur' }"
                        size="small">
                        <el-input v-model="groupData.name" class="group_data_name" maxlength="15"></el-input>
                    </el-form-item>
                    <el-form-item
                        prop="tags"
                        label="标签："
                        :rules="{ required: true, message: '标签不能为空', trigger: 'blur' }">
                        <div class="zw-el-tags">
                            <el-tag v-for="tag in groupData.tags" :key="tag" closable @close="handleClose(tag)">
                                {{ tag }}
                            </el-tag>
                            <el-input
                                v-if="inputVisible"
                                ref="InputRef"
                                v-model="inputValue"
                                class="create_label_input"
                                size="small"
                                maxlength="15"
                                placeholder="请输入标签内容"
                                @keyup.enter="handleInputConfirm"
                                @blur="handleInputConfirm">
                            </el-input>
                            <el-button v-else plan class="button-new-tag ml-1" size="small" @click="createLabel"
                                >新建标签</el-button
                            >
                        </div>
                    </el-form-item>
                    <el-form-item size="small">
                        <el-button type="primary" plain @click="saveLabel">保存新建标签</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </Dialog>
</template>
<script setup lang="ts">
import Dialog from './Dialog.vue';
import { ref, reactive, toRefs, nextTick, watchEffect, computed, watch } from 'vue';
import bus from '@/utils/bus';
import { ElInput, ElForm, ElMessage } from 'element-plus';
import { addTags, getTagsList, batchTagAdd, batchTagDel, editTextTag } from '@/api/common';
import { getSetionId } from '@/utils/utils';
const InputRef = ref<InstanceType<typeof ElInput>>();
const formRef = ref<InstanceType<typeof ElForm>>();

import { useStore } from '@/store';
const store = useStore();

const emit = defineEmits(['submit']);
const props = defineProps(['formTags', 'pageType']);
//是否编辑标签
const textEdit = ref(false);
const showCreatTag = ref(false);
// 添加标签
const batchTag = ref(false);
// 选中标签
const selectTags = ref([]);
// 选中复选框
const table = computed(() => {
    return store.getters['table'];
});
// 选择ID
const sectionIds = ref([]);
// 是否全选
const sectionAll = ref(false);

const labelList = ref([]);

const RadioTags = reactive({
    defaultVal: 0,
    seleTagOp: [
        {
            name: '批量打标签',
            value: 0,
            text: '若内容本身已有所选标签，则不针对此内容重复打标签'
        },
        {
            name: '批量移除标签',
            value: 1,
            text: '若内容本身没有所选标签，则不针对此内容重复移除标签'
        }
    ]
});
// 获取标签列表
const tagsList = async (tags: any[]) => {
    const arr: any[] = [];
    if (tags && tags.length > 0) {
        tags.forEach((item: any) => {
            arr.push(item.id || item.tag_id);
        });
    }
    const res = await getTagsList({
        page: 1,
        page_size: 1000
    });
    labelList.value = res.data;
    labelList.value.map((item: any) => {
        item.tags.forEach((k: any) => {
            if (arr.includes(k.id)) {
                k.selted = true;
            } else {
                k.selted = false;
            }
        });
    });
};

// 取消
const cancelHandel = () => {
    appDialog.visible = false;
    appDialog.title = '新建标签';
    showCreatTag.value = false;
    RadioTags.defaultVal = 0;
    batchTag.value = false;
    formRef.value?.resetFields();
};
const getCheckTag = (data: any) => {
    const arr: any[] = [];
    data.value.forEach((item: any) => {
        if (item.tags && item.tags.length > 0) {
            item.tags.forEach((tag: any) => {
                if (tag.selted) {
                    arr.push(tag);
                }
            });
        }
    });
    selectTags.value = arr;
};
bus.on('change', (data: any) => {
    sectionIds.value = getSetionId('id', data);
});

// 保存
const submitHandel = async () => {
    if (props.pageType == 'text') {
        watchFuncStop();
    }
    // 新增标签
    if (isGroup.value) {
        let flag = false;
        await formRef.value.validate(valid => (flag = valid));
        if (!flag) return;
        getCheckTag(labelList);
    } else {
        getCheckTag(labelList);
    }
    // 批量标签
    if (batchTag.value) {
        emit('submit', {
            tag_ids: selectTags.value,
            defaultVal: RadioTags.defaultVal
        });
    } else {
        emit('submit', selectTags.value);
    }
    cancelHandel();
};
const isGroup = ref(false);
// 弹框
const appDialog = reactive({
    visible: false,
    title: '选择标签',
    width: '700px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
});
const watchFuncStop = watch(
    () => appDialog.visible,
    newVal => {
        if (newVal) {
            tagsList(selectTags.value);
        }
    }
);
watch(table, table => {
    sectionAll.value = table.tableAll;
    sectionIds.value = getSetionId('id', table.tableData);
});

// 新建分组
const groupData = reactive({
    name: '',
    tags: []
});
// 新建标签
const inputValue = ref('');
const inputVisible = ref(false);
const handleClose = (tag: string) => {
    const data = groupData.tags.filter((item: string) => item !== tag);
    groupData.tags = data;
};
const createLabel = () => {
    inputVisible.value = true;
    nextTick(() => {
        InputRef.value!.input!.focus();
    });
};
const handleInputConfirm = () => {
    if (inputValue.value) {
        if (groupData.tags.includes(inputValue.value)) {
            ElMessage.warning('新建标签名不能重复');
            return;
        }
        groupData.tags.push(inputValue.value);
    }
    inputVisible.value = false;
    inputValue.value = '';
};
// 保存新建
const saveLabel = () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            try {
                const res = await addTags(groupData);
                ElMessage.success('创建标签成功');
                tagsList();
                formRef.value.resetFields();
            } catch (e) {}
        }
    });
};
defineExpose({
    sectionIds,
    textEdit,
    appDialog,
    batchTag,
    selectTags,
    showCreatTag,
    RadioTags
});
</script>
<style lang="scss" scoped>
.label_con {
    margin-top: 10px;

    .radio_list {
        &_item {
            &_text {
                margin-top: -3px;
            }

            &_icon {
                width: 14px;
                height: 14px;
                margin: -3px 0 0 6px;

                img {
                    width: 100%;
                    height: 100%;
                }
            }
        }

        :deep .el-radio__label {
            display: flex;
            align-items: center;
        }
    }

    .label_list {
        margin-bottom: 10px;
    }

    .label_title {
        margin-bottom: 5px;
        line-height: 20px;
    }

    .tag_item {
        display: inline-block;
        color: #969696;
        background: #fff;
        border: 1px solid #eaeaea;
        margin-right: 16px;
        margin-bottom: 10px;
        cursor: pointer;
        line-height: 20px;

        &_active {
            color: #ff6b00;
            border: 1px solid #ff6b00;
        }
    }

    .pad_4_10 {
        padding: 4px 10px;
    }

    .demo_dynamic {
        .group_data_name {
            width: 300px;
        }

        .create_label_input {
            width: 140px;
        }
    }

    .no_data {
        height: 300px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;

        .no_img {
            margin-left: 35px;
        }
    }
}
</style>
